//
//  AirTicketDanSearchList.swift
//  旅航ios
//
//  Created by tulip on 2021/5/5.
//

import UIKit
import SwiftyJSON

import HandyJSON

class AirTicketDanSearchList: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource, UIGestureRecognizerDelegate, MSSCalendarViewControllerDelegate {

    var priceArray:Array<Any>=[]
    
    var calenArr:Array<Any> = []
    var riliVC:MSSCalendarViewController!
    var timeType=""
    var priceType=""
    var airPortArr:Array<String>=[]
    var cabinArr:Array<Int>=[]
    var airNameArr:Array<String>=[]
    var dateStr:String?
    var airportData:[JSON]?
    var cabinData:[JSON]?
    var airNameData:[JSON]?
    var priceData:[JSON]?
    var noticeData:JSON?
    var Y:String=""
    var D:String=""
    var selectView:SelectTicketView!
    var dayArr:Array<(String,String,String)>!
    var highLight=0
    var sendDic:Dictionary<String,Any>!
    var data:[JSON]=[]
    @IBOutlet weak var table: UITableView!
    @IBOutlet weak var collect: UICollectionView!
    @IBOutlet weak var toAddress: UILabel!
    var toStr:String!
    var fromStr:String!
    var address1Code:String!
    var address2Code:String!
    @IBOutlet weak var FromAddress: UILabel!
    var selectCityView:SelectCityView!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor=UIColor.white
        // Do any additional setup after loading the view.
       
        let tap=UITapGestureRecognizer.init()
        tap.delegate=self
        tap.addTarget(self, action: #selector(selectCity))
        toAddress.addGestureRecognizer(tap)
        FromAddress.addGestureRecognizer(tap)
        toAddress.isUserInteractionEnabled=true
        FromAddress.isUserInteractionEnabled=true
        FromAddress.addGestureRecognizer(tap)
        toAddress.text=toStr
        FromAddress.text=fromStr
        
        let layout=HoFlowLayout.init()
        layout.itemSize=CGSize(width: 55, height: 70)
        layout.sectionInset=UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
        
        
        collect.collectionViewLayout=layout
        collect.delegate=self
        collect.dataSource=self
        collect.allowsSelection=true
        collect.register(UINib(nibName: "AirTicketTimeCell", bundle: nil), forCellWithReuseIdentifier: "AirTicketTimeCell")
        
        table.delegate=self
        table.dataSource=self
        table.register(UINib(nibName: "DanChengTableCell", bundle: nil), forCellReuseIdentifier: "DanChengTableCell")
        table.register(UINib(nibName: "NotifytionCell", bundle: nil), forCellReuseIdentifier: "NotifytionCell")
        table.backgroundColor=UIColor.init(hexString: "f2f1f6")
        
        
        Network.request(.searchTicket(parameters: sendDic)) { (JSON) in
            self.data=JSON["data"]["flightInfos"].array ?? []
            self.airportData=JSON["data"]["airPort"].array
            self.airNameData=JSON["data"]["airName"].array
            self.table.reloadData()
        } failure: { (err) in
            
        }

        
        let timeDate = stringFormatToDate(timeString: dateStr!, format: "yyyy-MM-dd")
        
        getMonthDate(date: timeDate, completion: { result in
            
            
            dayArr=result

            dateStr=dayArr[0].2
            let  dic=["departDate":dateStr ?? "","departCityCode":sendDic["departCityCode"] ?? "","arriveCityCode":sendDic["arriveCityCode"] ?? ""]
          
            Network.request(.searchPriceByday(dic)) { JSON in
                self.priceData=JSON["data"].arrayValue
                self.collect.reloadData()
            } failure: { err in
                
            }
            
            
        })
        
        Network.request(.notice) { JSON in
            self.noticeData=JSON["data"]
            self.table.reloadSections(IndexSet.init(integer: 0), with: UITableView.RowAnimation.automatic)
        } failure: { err in
            
        }

        
        
    }

    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        30
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
       
            return CGSize(width: 55, height:70)
       
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
       
        

        let cell:AirTicketTimeCell=collectionView.cellForItem(at: indexPath) as! AirTicketTimeCell
            
        dateStr=cell.dateStr
        
        let  newDic=["departDate":cell.dateStr ?? "","departCityCode":sendDic["departCityCode"] ?? "","arriveCityCode":sendDic["arriveCityCode"] ?? ""]
        
        Network.request(.searchPriceByday(newDic)) { JSON in
            let data=JSON["data"].arrayValue
            for a in data {
                if (self.priceData?.contains(a)) == true{
                    
                }else{
                    self.priceData?.append(a)
                }
            }
            self.collect.reloadData()
        } failure: { err in
            
        }
        
        
        highLight=indexPath.row
        
        Network.request(.searchTicket(parameters: newDic)) { (JSON) in
            self.data=JSON["data"]["flightInfos"].array ?? []
            self.airportData=JSON["data"]["airPort"].array
            self.airNameData=JSON["data"]["airName"].array
            self.table.reloadData()
        } failure: { (err) in
            
        }
    }
    
  
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:AirTicketTimeCell=collectionView.dequeueReusableCell(withReuseIdentifier: "AirTicketTimeCell", for: indexPath) as! AirTicketTimeCell
        
        cell.dayTime.text=dayArr[indexPath.row].0.substring(from: 5)
        cell.weekday.text=dayArr[indexPath.row].1
        cell.dateStr=dayArr[indexPath.row].2
        
        
        print("\(dayArr[indexPath.row].0.substring(from: 5)) \(dayArr[indexPath.row].1) \(dayArr[indexPath.row].2)")
        if (priceData?.count ?? 0) > 0{
            for a in priceData!  {
                if  a["departDate"].string == cell.dateStr{
                    let price=a["barePrice"].int ?? 0
                    if price == 0{
                        cell.price.text="暂无报价"

                    }else{
                        cell.price.text=String(price)
                    }
                   
                    break
                }
                cell.price.text="查价"
            }
        }
      
        
        if highLight == indexPath.row {
            cell.backgroundColor=UIColor.init(hexString: "307cf8")
            cell.layer.cornerRadius=3
            cell.price.textColor=UIColor.white
            cell.dayTime.textColor=UIColor.white
            cell.weekday.textColor=UIColor.white
        }else{
            cell.backgroundColor=UIColor.white
            cell.layer.cornerRadius=0
            cell.price.textColor=UIColor.init(hexString: "333333")
            cell.dayTime.textColor=UIColor.init(hexString: "333333")
            cell.weekday.textColor=UIColor.init(hexString: "333333")
        }
        

        return cell
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        2
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }
       
        return  data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 1 {
        
        let cell:DanChengTableCell=tableView.dequeueReusableCell(withIdentifier: "DanChengTableCell", for: indexPath) as! DanChengTableCell
        let imgUrl=data[indexPath.row]["carrierLogo"].string ?? ""
         cell.carrierLogo=imgUrl
            cell.img.kf.setImage(with: URL(string: imgUrl))
        cell.time1.text=data[indexPath.row]["dptTime"].string
        cell.time2.text=data[indexPath.row]["arrTime"].string
            
            cell.airTimeLabel.text=data[indexPath.row]["flightTimes"].string
            
            

            cell.airport1.text = (data[indexPath.row]["dptAirport"].string ?? "")! + (data[indexPath.row]["dptTerminal"].string!)
            cell.airport2.text = (data[indexPath.row]["arrAirport"].string ?? "")! + (data[indexPath.row]["arrTerminal"].string! )
        let AirlineName=data[indexPath.row]["flightNum"].string ?? ""
        let Aircraft=data[indexPath.row]["flightTypeFullName"].string ?? ""
        cell.company.text=AirlineName + " " + Aircraft
        
        let CabinAmount=data[indexPath.row]["cabinCount"].string ?? ""
        if CabinAmount == "A" {
            cell.leave.text=""
        }else{
            cell.leave.text="剩" + CabinAmount + "张"
        }
        let sale=data[indexPath.row]["discount"].double ?? 0
        cell.sale.text = String(sale) + "折"
        cell.price.text=String(data[indexPath.row]["barePrice"].int ?? 9999)
        cell.flightNo = data[indexPath.row]["flightNum"].string
            let ting=data[indexPath.row]["stopAirportName"].string ?? ""
            
            let tingCity=data[indexPath.row]["stopCityName"].string ?? ""
            if ting != ""{
                cell.ting.text="停 " + tingCity + "\n" + ting
            }
        
        return cell
            
        }
        
        let cell:NotifytionCell=tableView.dequeueReusableCell(withIdentifier: "NotifytionCell", for: indexPath) as! NotifytionCell
        cell.name.text=noticeData?["name"].string
        let html=noticeData?["content"].string ?? ""
        let attr = try! NSAttributedString.init(data: html.data(using: .unicode, allowLossyConversion: true)!, options: [.documentType:NSAttributedString.DocumentType.html], documentAttributes: nil)
       // attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor, range: NSMakeRange(0, 3))


        cell.content.attributedText  = attr
        return cell
        
    }
    
   
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return UITableView.automaticDimension
        }
        
        return 120
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            let cell:NotifytionCell=tableView.cellForRow(at: indexPath) as! NotifytionCell
            let view=NoticeView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
            view.setContent(titleStr: cell.name.text ?? "",contentStr: cell.content.text ?? "")
            self.view.addSubview(view)
        }else{
            let cell:DanChengTableCell=tableView.cellForRow(at: indexPath) as! DanChengTableCell
            let vc=OrderListVC.init()
            vc.sendDic=["token":TOKEN,"departDate":dateStr ?? "","departCityCode":sendDic["departCityCode"] ?? "","arriveCityCode":sendDic["arriveCityCode"] ?? "","flightNo":cell.flightNo ?? ""]
            vc.fromCtiy=fromStr
            vc.toCity=toStr
            vc.carrierLogo=cell.carrierLogo
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        self.tabBarController?.tabBar.isHidden=true
    }
 
    @IBAction func rili(_ sender: Any) {
  
        let dic = ["departDate":self.sendDic["departDate"] ?? "","departCityCode":self.sendDic["departCityCode"] ?? "" ,"arriveCityCode":self.sendDic["arriveCityCode"] ?? ""]
        
        
        Network.request(.searchPriceByday(dic)) { (JSON) in
            print("\(JSON)")
            if JSON["code"].int == 1 {
                self.calenArr.removeAll()
                guard let arr = JSONDeserializer<PriceCalendarModel>.deserializeModelArrayFrom(json: "\(JSON["data"])")else {
                    return
                }

                for model in arr{

                    self.calenArr.append(model as Any)
                }
                
                self.showCalendar()
            }
        } failure: { (err) in

        }

    }
    
    
    func showCalendar(){
        
        
        let vc=MSSCalendarViewController.init()
        vc.limitMonth = 2 ;// 显示几个月的日历
        vc.isDanCheng=true
        vc.type = MSSCalendarViewControllerType.nextType
        vc.beforeTodayCanTouch = false;// 今天之前的日期是否可以点击
        vc.afterTodayCanTouch = true;// 今天之后的日期是否可以点击
        vc.delegate = self
        vc.showPrice = true

         vc.priceArr = calenArr
        vc.modalTransitionStyle=UIModalTransitionStyle.flipHorizontal
        self.present(vc, animated: true, completion: nil)
        
//        riliVC=MSSCalendarViewController.init()
//        riliVC.limitMonth = 12 ;// 显示几个月的日历
//
//        riliVC.isDanCheng=true
//        riliVC.type = MSSCalendarViewControllerType.nextType
//        riliVC.beforeTodayCanTouch = false;// 今天之前的日期是否可以点击
//        riliVC.afterTodayCanTouch = true;// 今天之后的日期是否可以点击
//        riliVC.priceArr = calenArr
//        riliVC.delegate = self;
//
//        riliVC.modalTransitionStyle=UIModalTransitionStyle.flipHorizontal
//        self.present(riliVC, animated: true, completion: nil)
        
    }
    
//    func finishCalendar() {
//        // 计算价格
//        let dateStr=getTodayDate()
//
//        let  newDic=["departDate":dateStr ?? "","departCityCode":sendDic["departCityCode"] ?? "","arriveCityCode":sendDic["arriveCityCode"] ?? ""]
//
//        Network.request(.searchPriceByday(newDic)) { JSON in
//            let data=JSON["data"].arrayObject
//
//            self.calenArr.append(contentsOf: data ?? [])
//
//
//
//            self.riliVC.priceArr=self.calenArr
//            self.riliVC.showPrice=true
//            print("网络请求已经完成----------")
//            self.riliVC.collectionView.reloadData()
//        } failure: { err in
//
//        }
//    }
    
    func calendarViewConfirmClick(withStartDate startDate: Int, endDate: Int) {
        let mdateFormatter=DateFormatter.init()
        mdateFormatter.dateFormat="YYYY-MM-dd"
        dateStr=mdateFormatter.string(from: Date.init(timeIntervalSince1970: TimeInterval(startDate)))
        let  newDic=["departDate":dateStr ?? "","departCityCode":sendDic["departCityCode"] ?? "","arriveCityCode":sendDic["arriveCityCode"] ?? ""]
       
        Network.request(.searchTicket(parameters: newDic)) { (JSON) in
            self.data=JSON["data"]["flightInfos"].array ?? []
            self.airportData=JSON["data"]["airPort"].array
            self.airNameData=JSON["data"]["airName"].array
            self.table.reloadData()
        } failure: { (err) in
            
        }
        
        //更具某一天来算一个月的时间
        let timeDate = stringFormatToDate(timeString: dateStr!, format: "yyyy-MM-dd")
        getMonthDate(date: timeDate) {[weak self] result in
            self?.dayArr=result
            dateStr=result[0].2
            let  dic=["departDate":dateStr ?? "","departCityCode":sendDic["departCityCode"] ?? "","arriveCityCode":sendDic["arriveCityCode"] ?? ""]
          
            Network.request(.searchPriceByday(dic)) { JSON in
                self?.priceData=JSON["data"].arrayValue
                
                
                
                self!.highLight=0
                self?.collect.reloadData()
                
                
                
                self?.collect.scrollToItem(at: IndexPath(row: 0, section: 0), at: .left, animated: true)
                
//                let data=JSON["data"].arrayObject
//                self?.priceArray.append(contentsOf: data ?? [])

//                self?.riliVC.priceArr = self?.priceArray
//                self?.riliVC.collectionView.reloadData()
            } failure: { err in
                
            }
        }
        
    }
    
    @IBAction func back(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @IBAction func filter(_ sender: Any) {
        if selectView == nil {
            selectView=SelectTicketView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        }
        selectView.airNameData=airNameData
        selectView.airportData=airportData
        selectView.table1.reloadData()
        selectView.table3.reloadData()
        self.view.addSubview(selectView)
        selectView.propData={[weak self](arr1,arr2,arr3) in
            self?.airPortArr=arr1
            self?.cabinArr=arr2
            self?.airNameArr=arr3
            let  newDic=["departDate":self?.dateStr ?? "","departCityCode":self?.sendDic["departCityCode"] ?? "","arriveCityCode":self?.sendDic["arriveCityCode"] ?? "","airPort":self?.airPortArr,"cabin":self?.cabinArr,"airName":self?.airNameArr,"timeType":self?.timeType,"priceType":self?.priceType]
            
            Network.request(.searchTicket(parameters: newDic)) { (JSON) in
                self?.data=JSON["data"]["flightInfos"].array ?? []
                self?.airportData=JSON["data"]["airPort"].array
                self?.airNameData=JSON["data"]["airName"].array
                self?.table.reloadData()
            } failure: { (err) in
                
            }
            
        }
    }
    
    @IBAction func soonOrLate(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        if sender.isSelected {
            timeType="2"
        }else{
            timeType="1"
        }
        priceType=""
        let  newDic=["departDate":self.dateStr ?? "","departCityCode":self.sendDic["departCityCode"] ?? "","arriveCityCode":self.sendDic["arriveCityCode"] ?? "","airPort":self.airPortArr,"cabin":self.cabinArr,"airName":self.airNameArr,"timeType":self.timeType,"priceType":self.priceType]
        
        Network.request(.searchTicket(parameters: newDic)) { (JSON) in
            self.data=JSON["data"]["flightInfos"].array ?? []
            self.airportData=JSON["data"]["airPort"].array
            self.airNameData=JSON["data"]["airName"].array
            self.table.reloadData()
        } failure: { (err) in
            
        }
        
    }
    
    @IBAction func price(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        if sender.isSelected {
            priceType="2"
        }else{
            priceType="1"
        }
        timeType=""
        let  newDic=["departDate":self.dateStr ?? "","departCityCode":self.sendDic["departCityCode"] ?? "","arriveCityCode":self.sendDic["arriveCityCode"] ?? "","airPort":self.airPortArr,"cabin":self.cabinArr,"airName":self.airNameArr,"timeType":self.timeType,"priceType":self.priceType]
        
        Network.request(.searchTicket(parameters: newDic)) { (JSON) in
            self.data=JSON["data"]["flightInfos"].array ?? []
            self.airportData=JSON["data"]["airPort"].array
            self.airNameData=JSON["data"]["airName"].array
            self.table.reloadData()
        } failure: { (err) in
            
        }
        
        
    }
    

    @objc func selectCity(){
        
        if (selectCityView == nil){
            selectCityView=SelectCityView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: ScreenHight))
        }
        selectCityView.address1.text=FromAddress.text
        selectCityView.address2.text=toAddress.text
        selectCityView.timeBtn.setTitle(dateStr, for: .normal)
        selectCityView.address1Code=address1Code
        selectCityView.address2Code=address2Code
        self.view.addSubview(selectCityView)
        selectCityView.getNetwork={[weak self](dic,city1,city2) in
            self?.FromAddress.text=city1
            self?.toAddress.text=city2
            self?.dateStr=dic["departDate"] as! String
            self?.sendDic=["departDate":dic["departDate"] ?? "","departCityCode":dic["departCityCode"] ?? "","arriveCityCode":dic["arriveCityCode"] ?? "","cabin":self?.sendDic["cabin"] ?? ""]
            Network.request(.searchTicket(parameters: (self?.sendDic)!)) { (JSON) in
                self?.data=JSON["data"]["flightInfos"].array ?? []
                self?.airportData=JSON["data"]["airPort"].array
                self?.airNameData=JSON["data"]["airName"].array
                self?.table.reloadData()
            } failure: { (err) in
                
            }
            
            let timeDate = stringFormatToDate(timeString: (self?.dateStr)!, format: "yyyy-MM-dd")
            
            getMonthDate(date: timeDate, completion: { result in
                
                
            self?.dayArr=result

            self?.dateStr=self?.dayArr[0].2
            let  dic=["departDate":self?.dateStr ?? "","departCityCode":self?.sendDic["departCityCode"] ?? "","arriveCityCode":self?.sendDic["arriveCityCode"] ?? ""]
          
            Network.request(.searchPriceByday(dic)) { JSON in
                self?.priceData=JSON["data"].arrayValue
                self?.collect.reloadData()
            } failure: { err in
                
            }
                
                
            })
            
        }
        
    }
    
}
